package org.lisy.java.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * 
 * @author lisy
 */
public class ReadWriteLockOperate {
	
	private volatile static Map<String, Object> map = new HashMap<>();
	
	/**
	 * 读写锁演变过程:
	 * 1. 无锁状态多线程抢占资源 会出现问题
	 * 2. synchronized 和 reentrantLock，独占锁 每次只能一个线程来操作
	 * 3. ReentrantReadWriteLock 写写互斥，读写互斥，读读共享，同时多人读，提升性能
	 */

	/**
	 * ReetrantReadWriteLock特性: 
	 * 1. 锁降级:将写入锁降级为读锁，读锁不能升级为写锁(不可以在读锁中获取写锁)
	 * 2. 默认为非公平模式
	 * 3. 可重入
	 */
    private static ReadWriteLock lock = new ReentrantReadWriteLock();

    public static void main(String[] args) {
        // 写线程
        for (int i = 1; i <= 10; i++) {
            final int temp = i;
            new Thread(() -> {
            	write("No." + temp, "value_" + temp);
            }, "write thread-" + i).start();
        }
        // 读线程
        for (int i = 1; i <= 10; i++) {
            final int temp = i;
            new Thread(() -> {
            	read("No." + temp);
            },  "read thread-" + i).start();
        }
    }

    public static void write(String key, Object value) {
    	lock.writeLock().lock();
    	try {
    		System.out.println(Thread.currentThread().getName() + " write: " + key);
            map.put(key, value);
			TimeUnit.MILLISECONDS.sleep(10);
            System.out.println(Thread.currentThread().getName() + " write finish: " + value);
    	} catch (InterruptedException e) {
			e.printStackTrace();
    	} finally {
        	lock.writeLock().unlock();
    	}
    }

    public static void read(String key) {
    	lock.readLock().lock();
    	try {
    		System.out.println(Thread.currentThread().getName() + " read: " + key);
            Object obj = map.get(key);
            System.out.println(Thread.currentThread().getName() + " read finish: " + obj);
    	} finally {
    		lock.readLock().unlock();
    	}
    }
}
